package com.tricycle.scada.mqtt.configuration;

import com.alibaba.fastjson.JSON;
import lombok.extern.log4j.Log4j2;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.beans.factory.FactoryBean;

@Log4j2
public class MqttClientFactoryBean implements FactoryBean<MqttClient> {

    private MqttProperties properties;

    public MqttClientFactoryBean(MqttProperties properties) {
        this.properties = properties;
    }

    @Override
    public MqttClient getObject() throws Exception {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(false);
        options.setAutomaticReconnect(true);
        options.setConnectionTimeout(10);

        try {
            MqttClient client = new MqttClient(properties.getServerUri(), properties.getClientId());
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable throwable) {
                    logger.error("Mqtt connection lost.");
                }

                @Override
                public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
                    logger.info("Get message, length: {}.", JSON.parseArray(new String(mqttMessage.getPayload())).size());
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

                }
            });
            return client;
        } catch (MqttException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Class<?> getObjectType() {
        return null;
    }
}
